/**
 * CookieUtils.java
 * 
 * Project: IRS
 * 
 * Copyright Notice:
 * =============================================================================
 *    Copyright (c) 2007-2009 Shanghai Auto-Parts E-Procurement Co., Ltd.
 *        All rights reserved.
 *
 *    This software is the confidential and proprietary information of
 *        APEP Co., Ltd. ("Confidential Information").
 *        You shall not disclose such Confidential Information and shall use it
 *        only in accordance with the terms of the license agreement you entered
 *        into with APEP.
 *
 * Warning:
 * =============================================================================
 *
 */
package com.apep.permission;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangp 2009-12-21
 */
public class CookieUtils {

	public static final int DEFAULT_EXPIRY = 60 * 60 * 24 * 30; // 默认有效期一个月

	public static String getValue(HttpServletRequest request, String name) {
		Cookie[] tCookies = request.getCookies();

		String tValue = "";
		if (tCookies != null) {
			for (int i = 0; i < tCookies.length; i++) {
				Cookie tCookie = tCookies[i];
				if (name.equalsIgnoreCase(tCookie.getName())) {
					tValue = tCookie.getValue();
					break;
				}
			}
		}
		return tValue;
	}

	public static void setValue(HttpServletRequest request,
			HttpServletResponse response, String name, String value) {
		setValue(request, response, name, value, DEFAULT_EXPIRY);
	}

	public static void setValue(HttpServletRequest request,
			HttpServletResponse response, String name, String value, int expiry) {

		Cookie[] tCookies = request.getCookies();

		for (int i = 0; i < tCookies.length; i++) {
			Cookie tCookie = tCookies[i];
			if (name.equalsIgnoreCase(tCookie.getName())) {
				tCookie.setValue(value);
				tCookie.setMaxAge(expiry);
				response.addCookie(tCookie);
				// 设置有效期为一个月
				return;
			}
		}

		Cookie tNewCookie = new Cookie(name, value);
		tNewCookie.setMaxAge(expiry);

		response.addCookie(tNewCookie);
	}
}
